<template>
  <div class="order-wrap">
    <l-tabel
      :data="data.tableData"
      :columns="data.columns"
      :selectFlag="true"
      @selection-change="handleSelectionChange"
      :paginationFlag="true"
      :total="60"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
      <template #research="{ scope }">
        <span>{{ scope.row.research }}</span>
      </template>
      <template #status="{ scope }">
        <span>{{ scope.row.status == 0 ? '在线' : '离线' }}</span>
      </template>
      <template #operation="{ scope }">
        <el-button size="small" type="danger">编辑详情</el-button>
        <el-button size="small" type="danger">删除</el-button>
      </template>
    </l-tabel>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, getCurrentInstance } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import LTabel from '@/components/tabel.vue'
import { ElMessage, UploadInstance, UploadRequestOptions, UploadRawFile } from 'element-plus'

const data = reactive({
  disabled: false,
  fileList: [],
  imageUrl: '',
  multipleSize: 2,
  chunkSize: 2 * 1024 * 1024,
  percentage: 0,
  rowStyle: { height: '50px' },
  tableData: [
    { name: '林振涛', age: '18', sex: '男', research: '研发部', status: 1 },
    { name: '莫小鱼', age: '23', sex: '男', research: '研发部', status: 0 },
    { name: '林小琴', age: '24', sex: '女', research: '研发部', status: 1 }
  ],
  columns: [
    { attar: { label: '姓名', prop: 'name', width: '280' } },
    { attar: { label: '年龄', prop: 'age', width: '280' } },
    { attar: { label: '性别', prop: 'sex' } },
    { slot: 'research', attar: { label: '部门', prop: 'research', width: '280' } },
    { slot: 'status', attar: { label: '登录状态', prop: 'status', width: '280' } },
    { slot: 'operation', attar: { label: '操作', prop: 'operation', width: '280' } }
  ],
  pagination: {
    flag: true,
    page: 1,
    pageSize: 20,
    pageSizes: [20, 50, 100, 300]
  }
})
const multipleSelection = ref<any[]>([])

const uploadRef = ref<UploadInstance>()
// @ts-ignore
const { proxy } = getCurrentInstance()
const api = proxy.$api

const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
  console.log(multipleSelection.value, 'multipleSelection')
}
const handleSizeChange = (val: number) => {
  console.log(`${val} page`)
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
}
// 文件上传
// 判断是否需要分片
async function setMultiple(file: File, index: number = 0) {
  const { name, size } = file
  const fleSize = Math.ceil(size / data.chunkSize)
  // console.log(fleSize, 'fleSize');
  if (fleSize > data.multipleSize) {
    console.log('大于2M，开始分片')
    const [fname, fext] = name.split('.')
    // 获取当前片的起始值，从0开始
    const start = index * data.chunkSize
    console.log(fname, '====', fext)
    if (index > fleSize) {
      merge(file.name)
      return
    }
    const blob = file.slice(start, start + data.chunkSize)
    // console.log(blob, '文件大小');
    const blobName = `${fname}.${index}.${fext}`
    const formData = handleFormData(blob, blobName)
    // console.log(formData.get('file'), '=====》');
    console.log('开始上传', index)
    api.uploadBurstFile(formData).then(async (res) => {
      if (res.code == 200) {
        console.log(res, '上传成功')
        let percentage = GetPercent(index, fleSize)
        if (percentage == 100) {
          percentage = 99
        }
        data.percentage = percentage
        await setMultiple(file, ++index)
      }
    })
  } else {
    console.log('直接上传文件', fleSize)
    const formData = new FormData()
    formData.append('file', file)
    const res = await api.uploadFile(formData)
    if (res.code == 200) {
      console.log('上传成功')
    }
  }
  // 返回formData文件
  function handleFormData(file: Blob, name: string) {
    const blobFile = new File([file], name)
    console.log(blobFile, 'blobFile')

    const formData = new FormData()
    formData.append('file', blobFile)
    return formData
  }
  async function merge(name: string) {
    const res = await api.mergeFile({ fileName: name })
    console.log('合并成功!', res)
    data.percentage = 100
  }
  /**
   *
   * @param num 当前数
   * @param total 总数
   */
  function GetPercent(num: any, total: any) {
    num = parseFloat(num)
    total = parseFloat(total)
    if (isNaN(num) || isNaN(total)) {
      return 0
    }
    return total <= 0 ? 0 : Math.round((num / total) * 10000) / 100.0
  }
}
</script>

<style scoped lang="less">
.upload-demo {
  display: flex;
  align-items: center;
  padding: 0 30px;
  // background: pink;

  .submit {
    margin-left: 10px;
  }
}
</style>